﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Threading;
using System.Windows.Input;

using System.Windows.Media;
namespace Idlesoft.ShellAnywhere.Model
{
	public class DispatchingShellAnywhereModel : IShellAnywhereModel
	{
		#region ctors
		public DispatchingShellAnywhereModel(IShellAnywhereModel underlying)
		{
			_Dispatcher = Dispatcher.CurrentDispatcher;
			_Underlying = underlying;
			//_Underlying.TokenChanged += OnTokenChanged;
			//_Underlying.SetChanged += OnSetChanged;
			_Underlying.ShellActionsChanged += OnShellActionsChanged;
			_Underlying.OutputAppend += OnOutputAppend;
		}
		#endregion ctors

		#region props
		public HistoryMgr HistoryMgr
		{
			get { return _Underlying.HistoryMgr; }
		}
		public Posture Posture
		{
			get { return _Underlying.Posture; }
			set { _Underlying.Posture = value; }
		}
		public IActionMgr ActionMgr
		{
			get { return _Underlying.ActionMgr; }
		}
		#endregion props

		#region methods
		public void PostureChanged(Posture posture)
		{
			_Underlying.PostureChanged(posture);
		}
		public void OnStdOut(string text)
		{
			_Underlying.OnStdOut(text);
		}
		public void OnStdErr(string text)
		{
			_Underlying.OnStdErr(text);
		}

		public void Init()
		{
			_Underlying.Init();
		}
		public void End()
		{
			_Underlying.End();
		}
		private void OnShellActionsChanged(List<IShellAction> shellActions, int index)
		{
			Action action = () =>
			{
				if (ShellActionsChanged != null)
					ShellActionsChanged(shellActions, index);
			};
			_Dispatcher.BeginInvoke(DispatcherPriority.DataBind, action);
		}
		//private void OnTokenChanged(IActionToken token)
		//{
		//    System.Action action = () =>
		//    {
		//        if (TokenChanged != null)
		//            TokenChanged(token);
		//    };
		//    _Dispatcher.BeginInvoke(DispatcherPriority.DataBind, action);
		//}
		//private void OnSetChanged(ActionSet set)
		//{
		//    System.Action action = () =>
		//    {
		//        if (SetChanged != null)
		//            SetChanged(set);
		//    };
		//}

		private void OnOutputAppend(Brush color, string text)
		{
			System.Action action = () =>
			{
				if (OutputAppend != null)
					OutputAppend(color, text);
			};
			_Dispatcher.BeginInvoke(DispatcherPriority.DataBind, action);
		}		
		#endregion methods

		#region events
		//public event Action<IToken<IAction>> TokenChanged;
		//public event Action<ActionSet> SetChanged;
		public event Action<List<IShellAction>, int> ShellActionsChanged;
		public event Action<Brush, string> OutputAppend;
		#endregion events

		#region fields
		private readonly IShellAnywhereModel _Underlying;
		private readonly Dispatcher _Dispatcher;
		#endregion fields
	}
}
